package com.pi.shisan.service.config;

import com.pi.shisan.component.util.ComponentThread;
import com.pi.shisan.service.audio.AudioLevelManager;
import com.pi.shisan.service.schedule.ScheduleCreater;
import com.pi.shisan.service.util.ComponentManager;
import com.pi.shisan.service.util.SingleThreadCreator;
import org.apache.http.client.HttpClient;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.Closeable;
import java.io.IOException;

@Component
public class DestroyListener implements DisposableBean {

    @Autowired
    private AudioLevelManager audioLevelManager;

    @Autowired
    private ComponentManager componentManager;

    @Autowired
    private HttpClient httpClient;

    @Autowired
    private ScheduleCreater scheduleCreater;

    private boolean isShutdownSystem;

    @Override
    public void destroy() throws Exception {
        try {
            audioLevelManager.shutdown();
        } catch (Exception e) {
        }
        try {
            componentManager.exit();
        } catch (Exception e) {
        }
        try {
            ComponentThread.exit();
        } catch (Exception e) {
        }
        try {
            if (httpClient instanceof Closeable) {
                ((Closeable) httpClient).close();
            }
        } catch (Exception e) {
        }

        try {
            scheduleCreater.getScheduler().shutdown();
        } catch (SchedulerException e) {
        }

        try {
            SingleThreadCreator.getVacationRefresher().exit();
        } catch (Exception e) {
        }

        try {
            SingleThreadCreator.getVolumeTran().exit();
        } catch (Exception e) {
        }
        if (isShutdownSystem) {
            try {
                Runtime.getRuntime().exec("sudo shutdown now");
            } catch (Exception e) {
            }
        }
    }

    public void setToShutdownSystem() {
        this.isShutdownSystem = true;
    }
}
